//
//  SegmentBar.m
//  YanXiuWang
//
//  Created by 慧趣小歪 on 17/1/12.
//  Copyright © 2017年 小分队. All rights reserved.
//

#import "SegmentBar.h"

@interface SegmentBar ()

@property (nonatomic, strong) NSMutableArray<UILabel *> *labels;
@property (nonatomic, weak) UIView *bottomLine;
@property (nonatomic, weak) UITapGestureRecognizer *tap;

@property (nonatomic, assign) NSInteger startIndex;
@property (nonatomic, assign) NSInteger endIndex;
@property (nonatomic, assign) CGFloat percent;

@end

@implementation SegmentBar

- (void)from:(NSInteger)startIndex to:(NSInteger)endIndex percent:(CGFloat)ePercent {
    if (startIndex < 0 || startIndex >= _labels.count) return;
    if (endIndex   < 0 || endIndex   >= _labels.count) return;
    if (ePercent   < 0 || ePercent   > 1) return;
    
    _startIndex = startIndex;
    _endIndex = endIndex;
    _percent = ePercent;
    
    CGFloat sPercent = 1 - ePercent;
    
    CGFloat w1 = CGRectGetWidth(_labels[startIndex].frame) * sPercent;
    CGFloat w2 = CGRectGetWidth(_labels[endIndex].frame) * ePercent;
    
    CGFloat cx = (_labels[endIndex].center.x - _labels[startIndex].center.x) * ePercent + _labels[startIndex].center.x;
    
    CGRect frame = _bottomLine.frame;
    frame.size.width = ceil(w1 + w2);
    frame.origin.x = ceil(cx - frame.size.width / 2);
    
    _bottomLine.frame = frame;
}

- (void)setBottomLineFrame:(CGRect)frame {
    if (_percent < 0 || _percent > 1 || _startIndex < 0 || _startIndex >= _labels.count || _endIndex < 0 || _endIndex >= _labels.count) {
        _bottomLine.frame = frame;
    } else {
        [self from:_startIndex to:_endIndex percent:_percent];
    }
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self != nil) {
        self.enabled = YES;
    }
    return self;
}

- (void)setEnabled:(BOOL)enabled {
    _enabled = enabled;
    _tap.enabled = enabled;
}

- (void)willMoveToWindow:(UIWindow *)newWindow {
    [super willMoveToWindow:newWindow];
    _bottomLine.backgroundColor = self.tintColor;
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];
    [_bottomLine removeFromSuperview];
    
    if (newSuperview == nil) return;
    
    CGSize size = self.bounds.size;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, size.height - _bottomLineHeight, size.width / 4, _bottomLineHeight)];
    view.backgroundColor = self.tintColor;
    [self addSubview:view];
    _bottomLine = view;
    
    if (_tap != nil) return;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapped:)];
    [self addGestureRecognizer:tap];
    tap.enabled = _enabled;
    _tap = tap;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
- (void)onTapped:(UITapGestureRecognizer *)tap {
    CGFloat x = [tap locationInView:self].x;
    for (NSInteger i = 0; i<_labels.count; i++) {
        if (x < CGRectGetMinX(_labels[i].frame) || CGRectGetMaxX(_labels[i].frame) < x) continue;
        if (self.index == i) return;
        self.index = i;
        if (_action != nil) [_target performSelector:_action withObject:@(i)];
        break;
    }
}
#pragma clang diagnostic pop

- (void)setIndex:(NSInteger)index {
    _percent = -1;

    if (_index == index) return;
    
    _keepWidth = _keepWidth == 0 ? 70 : _keepWidth;
    
    __block NSInteger newIndex = index;
    __block NSInteger oldIndex = _index;
    _index = index;
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.35 animations:^{
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        if (oldIndex < _labels.count) {
            _labels[oldIndex].textColor = _color ?: [UIColor darkGrayColor];
            CGRect frame = _bottomLine.frame;
            if (newIndex < oldIndex && newIndex < _labels.count) {
                frame.origin.x = CGRectGetMinX(_labels[newIndex].frame);
                frame.size.width = CGRectGetMaxX(_bottomLine.frame) - CGRectGetMinX(frame);
            } else if (newIndex > oldIndex && newIndex < _labels.count) {
                frame.size.width = CGRectGetMaxX(_labels[newIndex].frame) - CGRectGetMinX(frame);
            }
            [weakSelf setBottomLineFrame:frame];
        }
        if (newIndex < _labels.count) {
            _labels[newIndex].textColor = self.tintColor;
            CGRect frame = _labels[newIndex].frame;
            if (!CGRectContainsRect(CGRectInset(self.bounds, _keepWidth, 0), frame)) {
                if (newIndex > oldIndex) {
                    NSInteger nextIndex = MIN(_labels.count - 1, newIndex + 1);
                    [self scrollRectToVisible:_labels[nextIndex].frame animated:NO];
                } else if (_labels.count > 0) {
                    NSInteger nextIndex = MAX(0, newIndex - 1);
                    [self scrollRectToVisible:_labels[nextIndex].frame animated:NO];
                }
            }
        }
    }];
    [UIView animateWithDuration:0.25 animations:^{
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDelay:0.1];
        if (newIndex < _labels.count) {
            CGRect frame = _bottomLine.frame;
            frame.origin.x = _labels[newIndex].frame.origin.x;
            frame.size.width = _labels[newIndex].frame.size.width;
            [weakSelf setBottomLineFrame:frame];
        }
    }];
}

- (void)resetLabels {
    [_labels makeObjectsPerformSelector:@selector(removeFromSuperview)];
    _percent = -1;
    // 如果移动偏移超出 一页数量最大, 则恢复到0
    _labels = [NSMutableArray arrayWithCapacity:_titles.count];
    for (NSInteger i = 0; i<_titles.count; i++) {
        UILabel *label = [UILabel new];
        label.font = _font ?: [UIFont systemFontOfSize:16];;
        label.textColor = i == _index ? self.tintColor : (_color ?: [UIColor darkGrayColor]);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = _titles[i];
        [self addSubview:label];
        [_labels addObject:label];
    }
}

- (void)setTitles:(NSArray *)titles {
    _titles = titles;
    
    if (_labels.count != _titles.count) {
        [self resetLabels];
    }
    
    if (_index >= _titles.count) _index = 0;
    
    for (NSInteger i = 0; i<_titles.count; i++) {
        _labels[i].text = _titles[i];
    }
    [self layoutSubviews];
}

- (void)normalLayoutSubviews {
    UIFont *font = _font ?: [UIFont systemFontOfSize:16];
    
    //CGFloat selfWidth = CGRectGetWidth(self.bounds);
    CGFloat height = CGRectGetHeight(self.frame) - _bottomLineHeight;
    CGFloat lastX = _tabInterval / 2;
    
    for (NSInteger i = 0; i<_titles.count; i++) {
        CGFloat width = [_titles[i] boundingRectWithSize:CGSizeZero options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size.width + _tabInterval;
        
        _labels[i].frame = CGRectMake(i == 0 ? 0 :lastX, _titleOffset + _bottomLineHeight, ceil(width), height - _bottomLineHeight);
        _labels[i].text = _titles[i];
        
        lastX = i == 0 ? width : width + lastX;
        
        //            lastX += width;
        
    }
    [self setContentSize:CGSizeMake(lastX , height + _bottomLineHeight)];
    if (_index < _labels.count) {
        
        [self setBottomLineFrame:CGRectMake(CGRectGetMinX(_labels[_index].frame), height, CGRectGetWidth(_labels[_index].frame), _bottomLineHeight)];
    }
}

- (void)averageLayoutSubviews {
    UIFont *font = _font ?: [UIFont systemFontOfSize:16];
    
    if (_titles.count == 0) return;
    //CGFloat selfWidth = CGRectGetWidth(self.bounds);
    CGFloat height = CGRectGetHeight(self.frame) - _bottomLineHeight;
    CGFloat itemWidth = CGRectGetWidth(self.frame) / _titles.count;
    
    //    CGFloat lastX = _tabInterval / 2;
    
    for (NSInteger i = 0; i<_titles.count; i++) {
        CGFloat width = [_titles[i] boundingRectWithSize:CGSizeZero options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size.width + _tabInterval;
        
        _labels[i].frame = CGRectMake(ceil(itemWidth - width) / 2 + ceil(i * itemWidth), _titleOffset + _bottomLineHeight, ceil(width), height - _bottomLineHeight);
        _labels[i].text = _titles[i];
        
    }
    [self setContentSize:CGSizeMake(CGRectGetWidth(self.bounds), height + _bottomLineHeight)];
    if (_index < _labels.count) {
        [self setBottomLineFrame:CGRectMake(CGRectGetMinX(_labels[_index].frame), height, CGRectGetWidth(_labels[_index].frame), _bottomLineHeight)];
    }
}

- (void) layoutSubviews {
    [super layoutSubviews];
    
    if (_averageStyle) {
        [self averageLayoutSubviews];
    } else {
        [self normalLayoutSubviews];
    }
}

- (void)setTintColor:(UIColor *)tintColor {
    [super setTintColor:tintColor];
    if (_index < _labels.count) _labels[_index].textColor = tintColor;
    _bottomLine.backgroundColor = tintColor;
}

- (void)setFont:(UIFont *)font {
    _font = font;
    [_labels makeObjectsPerformSelector:@selector(setFont:) withObject:font];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
